const UserPrisma = require('../models/UserPrisma');
const IpLocationService = require('./IpLocationService');

function buildLocationPayload(location) {
  if (!location || !location.province) {
    return null;
  }

  return {
    last_known_ip: location.ip,
    last_known_province: location.province,
    last_known_city: location.city || null,
    location_updated_at: new Date()
  };
}

async function maybeUpdateUserLocation(user, location) {
  if (!user) {
    return user;
  }

  if (!location || !location.province) {
    return user;
  }

  const shouldRefresh = IpLocationService.shouldRefreshUserLocation(user, location);
  if (!shouldRefresh) {
    return user;
  }

  const payload = buildLocationPayload(location);
  if (!payload) {
    return user;
  }

  return await UserPrisma.update(user.id, payload);
}

async function resolveLocationFromRequest(req) {
  return await IpLocationService.resolveLocationFromRequest(req);
}

async function updateUserLocationFromRequest(req, user) {
  const location = await resolveLocationFromRequest(req);
  const updatedUser = await maybeUpdateUserLocation(user, location);
  return {
    user: updatedUser || user,
    location
  };
}

module.exports = {
  buildLocationPayload,
  maybeUpdateUserLocation,
  resolveLocationFromRequest,
  updateUserLocationFromRequest
};
